package com.tencent.wxcloudrun.controller;

import com.tencent.wxcloudrun.model.support.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.tencent.wxcloudrun.dto.CounterRequest;
import com.tencent.wxcloudrun.model.Counter;
import com.tencent.wxcloudrun.service.CounterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * counter控制器
 */
@RestController
public class CounterController {

    final CounterService counterService;
    final Logger logger;

    public CounterController(@Autowired CounterService counterService) {
        this.counterService = counterService;
        this.logger = LoggerFactory.getLogger(CounterController.class);
    }


    /**
     * 获取当前计数
     *
     * @return API response json
     */
    @GetMapping(value = "/api/count")
    R get(Integer id) {
        logger.info("/api/count get request");
        try {
          Counter counter = counterService.get(id);
          return R.success(counter);
        }catch (Exception e){
          return R.fail(e.getMessage());
        }
    }


    /**
     * 更新计数，自增或者清零
     *
     * @param request {@link CounterRequest}
     * @return API response json
     */
    @PostMapping(value = "/api/count")
    R add(@RequestBody CounterRequest request) {
        logger.info("/api/count post request: {}", request);
        try {
          counterService.add(request);
          return R.success();
        }catch (Exception e){
          return R.fail(e.getMessage());
        }
    }

}